package com.mjk.common.core.health;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

/**
 * rabbitmq 健康检测
 */
@Configuration
@ConditionalOnProperty(value="bee.rmq",havingValue = "true",matchIfMissing = false)
public class RabbitHealthIndicator extends AbstractHealthIndicator {
    private final RabbitTemplate rabbitTemplate;

    public RabbitHealthIndicator(RabbitTemplate rabbitTemplate) {
        super("Rabbit health check failed");
        Assert.notNull(rabbitTemplate, "RabbitTemplate must not be null");
        this.rabbitTemplate = rabbitTemplate;
    }

    protected void doHealthCheck(Health.Builder builder) throws Exception {
        builder.up().withDetail("version", this.getVersion());
    }

    private String getVersion() {
        return (String)this.rabbitTemplate.execute((channel) -> {
            return channel.getConnection().getServerProperties().get("version").toString();
        });
    }
}
